package ch.headshot.photomap.client.editor.view;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

import ch.headshot.photomap.client.gpx.Gpx;
import ch.headshot.photomap.client.gpx.Track;

import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.ComplexPanel;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.StackPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class GpxStructure extends Composite {

	private static GpxStructure instance;
	private VerticalPanel tracks;
	private final Map map;
	private Gpx gpx;

	public static GpxStructure getInstance() {
		if (instance == null) {
			instance = new GpxStructure(Map.getInstance());
		}

		return instance;
	}

	private GpxStructure(Map widget) {
		this.map = widget;
		init();
	}

	private void init() {
		StackPanel panel = new StackPanel();
		panel.setWidth("200px");
		initWidget(panel);
		panel.add(getTracks(), "Tracks");
		panel.add(getNotYetImplemented(), "Routes");
		panel.add(getNotYetImplemented(), "WayPoints");
	}

	private Widget getNotYetImplemented() {
		return new Label("Not yet implemented");
	}

	private VerticalPanel getTracks() {
		if (tracks == null) {
			tracks = new VerticalPanel();
		}
		return tracks;
	}

	public void setGpx(Gpx gpx) {
		this.gpx = gpx;
		getTracks().clear();
		Button selectAll = new Button("select All");
		selectAll.addClickListener(new ClickListener() {

			public void onClick(Widget sender) {
				Stack<ComplexPanel> panels = new Stack();
				panels.push(getTracks());
				while (!panels.isEmpty()) {
					ComplexPanel wid = panels.pop();
					for (int i = 0; i < wid.getWidgetCount(); i++) {
						Widget w = wid.getWidget(i);
						if (w instanceof TrackStructure) {
							((TrackStructure) w).setChecked(true);
						} else if (w instanceof ComplexPanel) {
							panels.add((ComplexPanel) w);
						}
					}
				}
			}
		});
		getTracks().add(selectAll);
		map.clear();
		selectedTracks.clear();
		for (Track track : gpx.getTracks()) {
			getTracks().add(new TrackStructure(track));
		}
	}

	List<Track> selectedTracks = new ArrayList();

	public List<Track> getSelectedTracks() {
		return selectedTracks;
	}

	public Gpx getGpx() {
		return gpx;
	}

	public void refresh() {
		setGpx(gpx);
	}
}
